package com.shadt.core.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.shadt.core.dao.ResourceDao;
import com.shadt.core.dao.UserDao;
import com.shadt.core.entity.Resource;
import com.shadt.core.entity.Role;
import com.shadt.core.entity.User;
import com.shadt.core.model.Tree;
import com.shadt.core.service.UserService;
import com.shadt.core.util.MD5Util;
import com.shadt.core.util.SessionInfo;
import com.shadt.core.vo.UserVo;

/**
 * 用户业务层实现类
 * 
 * @author SongR
 * 
 */
@Service
public class UserServiceImpl implements UserService {
	@Autowired
	UserDao userDao;
	@Autowired
	ResourceDao resourceDao;

	/**
	 * 实现用户登录
	 */
	public UserVo login(UserVo userVo) {
		Map<String, Object> params = new HashMap<String, Object>();
		User user = null;
		if (null != userVo) {
			params.put("name", userVo.getName());
			params.put("pwd", MD5Util.md5(userVo.getPwd()));
			user = userDao
					.get("from User t where t.name = :name and t.pwd = :pwd and isDelete !='1'",
							params);
			if (null != user) {
				BeanUtils.copyProperties(user, userVo);
			} else {
				return null;
			}
		}
		return userVo;
	}

	/**
	 * 实现用户注册
	 */
	synchronized public void reg(UserVo vo) throws Exception {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("name", vo.getName());
		if (userDao.count("select count(*) from User t where t.name = :name",
				params) > 0) {
			throw new Exception("登录名已存在！");
		} else {
			User u = new User();
			u.setId(UUID.randomUUID().toString());
			u.setName(vo.getName());
			u.setNikeName(vo.getNikeName());
			u.setPwd(MD5Util.md5(vo.getPwd()));
			u.setCreatedatetime(new Date());
			u.setEmail(vo.getEmail());
			u.setPhone(vo.getPhone());
			u.setIsAvailable("0");
			u.setIsDelete("0");
			userDao.save(u);
		}
	}

	/**
	 * 实现用户名是否存在验证
	 * 
	 * @param name
	 * @return
	 */
	public boolean checkUserName(String name) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("name", name);
		if (userDao.count("select count(*) from User t where t.name = :name",
				params) > 0) {
			return false;
		}
		return true;
	}

	/**
	 * 实现密码是否正确验证
	 * 
	 * @param name
	 * @return
	 */
	public boolean checkPwd(String oldpwd,String id) {
		User u = userDao.get(User.class,id);
		if(u.getPwd().equals(MD5Util.md5(oldpwd))){
			return true;
		}
		return false;
	}

	/**
	 * 实现根据当前登陆用户获取可访问栏目
	 * 
	 * @param id
	 * @return
	 */
	public List<String> resourceList(String id) {
		List<String> resourceList = new ArrayList<String>();
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("id", id);
		User t = userDao
				.get("from User t join fetch t.roles role join fetch role.resources resource where t.id = :id",
						params);
		if (t != null) {
			Set<Role> roles = t.getRoles();
			if (roles != null && !roles.isEmpty()) {
				for (Role role : roles) {
					Set<Resource> resources = role.getResources();
					if (resources != null && !resources.isEmpty()) {
						for (Resource resource : resources) {
							if (resource != null && resource.getUrl() != null) {
								resourceList.add(resource.getUrl());
							}
						}
					}
				}
			}
		}
		return resourceList;
	}

	/**
	 * 实现根据当前登陆用户获取可访问栏目菜单
	 */
	public List<Tree> getMenuList(SessionInfo sessionInfo) {
		List<Resource> l = null;
		List<Tree> lt = new ArrayList<Tree>();
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("resourceTypeId", "0");// 菜单类型的资源

		if (sessionInfo != null) {
			params.put("userId", sessionInfo.getId());// 自查自己有权限的资源
			l = resourceDao
					.find("select distinct t from Resource t join fetch t.resourceType type join fetch t.roles role join role.users user where type.id = :resourceTypeId and user.id = :userId order by t.seq",
							params);
		} else {
			l = resourceDao
					.find("select distinct t from Resource t join fetch t.resourceType type where type.id = :resourceTypeId order by t.seq",
							params);
		}

		if (l != null && l.size() > 0) {
			for (Resource r : l) {
				Tree tree = new Tree();
				BeanUtils.copyProperties(r, tree);
				// 设置父节点
				if (r.getResource() != null) {
					tree.setPid(r.getResource().getId());
				}
				tree.setText(r.getName());
				tree.setIconCls(r.getIcon());
				// 设置借点url属性
				Map<String, Object> attr = new HashMap<String, Object>();
				attr.put("url", r.getUrl());
				tree.setAttributes(attr);
				//
				lt.add(tree);
			}
		}
		return lt;
	}

	/**
	 * 实现获取所有用户
	 */
	public List<UserVo> getAllUsers(String str, Integer pageNo, Integer rows) {
		List<UserVo> ul = new ArrayList<UserVo>();
		String hql = " from User t ";
		List<User> l = userDao.find(hql + whereHql(str), pageNo / rows + 1,
				rows);
		if (null != l && l.size() > 0) {
			for (User t : l) {
				UserVo u = new UserVo();
				BeanUtils.copyProperties(t, u);
				Set<Role> roles = t.getRoles();
				if (roles != null && !roles.isEmpty()) {
					String roleIds = "";
					String roleNames = "";
					boolean b = false;
					for (Role tr : roles) {
						if (b) {
							roleIds += ",";
							roleNames += ",";
						} else {
							b = true;
						}
						roleIds += tr.getId();
						roleNames += tr.getName();
					}
					u.setRoleIds(roleIds);
					u.setRoleNames(roleNames);
				}
				ul.add(u);
			}
		}
		return ul;
	}

	/**
	 * 实现根据条件获取记录总数
	 */
	public Long getUsersCount(String str) {
		return userDao.count("select count(*) from User t" + whereHql(str));
	}

	/**
	 * 实现根据用户id删除用户
	 */
	public boolean del(String id) {
		User u = new User();
		try {
			u = userDao.get(User.class, id);
			u.setIsDelete("1");
			userDao.update(u);
		} catch (Exception e) {
			return false;
		}
		return true;
	}

	/**
	 * 实现修改密码
	 */
	public boolean editPwd(String id, UserVo vo) {
		try {
			User u = userDao.get(User.class,id);
			u.setPwd(MD5Util.md5(vo.getPwd()));
			u.setModifydatetime(new Date());
			userDao.save(u);
			return true;
		} catch (Exception e) {
			return false;
		}
	}
	/**
	 * 实现根据用户id获取用户信息
	 */
	public UserVo getUserById(String id) {
		User u = userDao.get(User.class,id);
		UserVo userVo = new UserVo();
		if(null!= u){
			BeanUtils.copyProperties(u, userVo);
		}
		return userVo;
	}
	/*************************************************************************************************************************************/

	/**
	 * 组装where条件
	 * 
	 * @param user
	 * @param params
	 * @return
	 */
	private String whereHql(String str) {
		String hql = " where isDelete != '1' ";
		if (null != str && !"".equals(str)) {
			hql += " and  t.name like   '%" + str + "%' ";
		}
		// hql+=" order by nikeName";
		// if (user.getName() != null) {
		// hql += " and t.name like :name";
		// params.put("name", "%%" + user.getName() + "%%");
		// }
		return hql;
	}
}
